package XML;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
 * Responsabilità: scrive o modifica un file Xml a seconda se esiste o no
 */
public class XMLWriter {

	boolean existed = false;

	public void write(String files, String Attributo1, double Attributo2, String Attributo3, boolean Attributo4) {

		try {
			
			File file = new File(files);

			existed = false;
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(file);		
			
				Node root = doc.getElementsByTagName("ElementoPadre").item(0);

				Element player = doc.createElement("PrimoLivello");
				root.appendChild(player);

				Attr attr = doc.createAttribute("Attributo");
				attr.setValue(Attributo1);
				player.setAttributeNode(attr);
				
				Attr attr2 = doc.createAttribute("Attributo2");
				attr2.setValue(String.valueOf(Attributo2));
				player.setAttributeNode(attr2);
				
				Attr attr3 = doc.createAttribute("Attributo3");
				attr3.setValue(String.valueOf(Attributo3));
				player.setAttributeNode(attr3);
				
				Attr attr4 = doc.createAttribute("Attributo4");
				attr4.setValue(String.valueOf(Attributo4));
				player.setAttributeNode(attr4);
				

				existed = true;

			

			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(file);
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

			transformer.transform(source, result);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}